import type { NextApiRequest, NextApiResponse } from "next";

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method === "POST") {
    createValidation(req, res);
  }
  if (req.method === "GET") {
    getValidationList(req, res);
  }
}

async function getValidationList(req: NextApiRequest, res: NextApiResponse) {
  const records = await prisma.validation.findMany();
  res.json(records);
}

async function createValidation(req: NextApiRequest, res: NextApiResponse) {
  try {
    const input = {
      name: req.body.name,
      group: req.body.group,
      virtual: req.body.virtual === "true",
      noise: Number.parseFloat(req.body.noise),
      indicator1: Number.parseFloat(req.body.indicator1),
      indicator2: Number.parseFloat(req.body.indicator2),
    };
    const record = await prisma.validation.create({ data: input });
    return res.json({ code: 0, message: "创建成功", id: record.id });
  } catch (err) {
    console.log(err);
    res.json({ code: 500, message: "创建失败", err });
  }
}
